package cn.enaium.message.specific;

import cn.enaium.message.config.JdbcConfig;
import cn.enaium.message.entity.Message;
import cn.enaium.message.entity.Muser;
import cn.enaium.message.repository.MessageRepository;
import cn.enaium.message.repository.MuserRepository;
import org.apache.ibatis.session.SqlSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class AddMessage {
    @GetMapping(value = "/addmessage")
    public int SaveMessage(String author,String message,String uid){
        JdbcConfig jdbcConfig = new JdbcConfig();
        SqlSession sqlSession= jdbcConfig.getSqlSession();
        //获取代理对象
        MessageRepository messageRepository=sqlSession.getMapper(cn.enaium.message.repository.MessageRepository.class);
        String mtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Message m = new Message();
        m.setMessage(message);
        if (author.equals("")) {
            MuserRepository muserRepository=sqlSession.getMapper(cn.enaium.message.repository.MuserRepository.class);
            Muser muser = muserRepository.findByIdMuser(Long.parseLong(uid));
            m.setAuthor(muser.getName());
        }else {
            m.setAuthor(author);
        }
        m.setUid(Long.valueOf(uid));
        m.setMtime(mtime);
        int result = messageRepository.saveMessage(m);
        return UpYesOrNo(jdbcConfig, sqlSession, result);
    }

    static int UpYesOrNo(JdbcConfig jdbcConfig, SqlSession sqlSession, int result) {
        if (result > 0) {
            //关闭Sql链接
            sqlSession.commit();
            jdbcConfig.sqlSessionCommit();
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return result;
        }else {
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return 0;
        }
    }
}
